<template>
  <div class="pos-container" tabindex="0" ref="posContainerRef" @keydown="containerKeyDown">
    <!-- 顶部导航栏 -->
    <div class="pos-header">
      <div class="logo">云POS</div>
      <div class="store-info">陕西临潼西大街人本专卖店 <span class="store-code">029388</span></div>
      <div class="header-actions">
        <el-button type="primary">收银</el-button>
        <el-button @click="navigateTo('/store-management')">店务管理</el-button>
        <el-button @click="showUnderConstruction('仓储管理')">仓储管理</el-button>
        <el-button @click="showUnderConstruction('店长导航')">店长导航</el-button>
        <el-button @click="showUnderConstruction('报表')">报表</el-button>
        <div class="header-icons">
          <el-icon><CircleCheck /></el-icon>
          <el-icon><Monitor /></el-icon>
          <el-icon><Right /></el-icon>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="order-info">
      <div class="order-details">
        <div class="order-item">小票编号:232802938PM250515135918003</div>
        <div class="order-item">销售日期: 2025-05-15</div>
        <div class="order-item">
          零售类型: 
          <el-select v-model="retailType" placeholder="请选择">
            <el-option label="正常零售" value="正常零售"></el-option>
          </el-select>
        </div>
        <div class="order-item">
          营业员:
          <el-input v-model="salesPerson" placeholder="申申"></el-input>
        </div>
        <div class="order-item">
          会员/VIP号:
          <el-input v-model="memberNumber" placeholder=""></el-input>
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="goods-table">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        height="350"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="序号" width="60" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" width="120" />
        <el-table-column prop="color" label="颜色" width="100" />
        <el-table-column prop="size" label="尺码" width="100" />
        <el-table-column prop="retailPrice" label="零售价" width="100" />
        <el-table-column prop="discount" label="零售折扣" width="100" />
        <el-table-column prop="actualPrice" label="应收价" width="100" />
        <el-table-column prop="quantity" label="数量" width="80">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.quantity" 
              :min="1" 
              :max="99"
              size="small"
              @change="(val) => handleQuantityChange(scope.row, val)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实收价" width="100" />
        <el-table-column prop="totalAmount" label="实收金额" width="100" />
        <el-table-column prop="salesperson" label="营业员" width="100" />
        <el-table-column prop="saleType" label="销售类型" width="100" />
        <el-table-column prop="unique" label="唯一码" width="100" />
        <el-table-column fixed="right" label="可执行促销" width="160">
          <template #default="scope">
            <div v-if="scope.row.id === 1">
              <div class="promotion-tag new">新品7折</div>
              <div class="promo-date">2023-04-20 00:00:00.0 ~ 2027-05-31 23:59:59.0</div>
            </div>
            <div v-if="scope.row.id === 3">
              <div class="promotion-tag store">自营店一口价39-199 (8.21)</div>
              <div class="promo-date">2024-06-28 00:00:00.0 ~ 2040-07-31 23:59:59.0</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部功能区 -->
    <div class="pos-footer">
      <div class="input-area">
        <div class="input-prompt">
          <el-input 
            v-model="productCodeInput" 
            placeholder="请输入商品编码 F12" 
            @keyup.enter="searchProduct"
            class="product-input"
            clearable
            ref="productInputRef"
          ></el-input>
        </div>
        <div class="sale-type">
          <span>销售类型</span>
          <el-select v-model="saleTypeValue" placeholder="正常零售">
            <el-option label="正常零售" value="正常零售"></el-option>
            <el-option label="会员零售" value="会员零售"></el-option>
            <el-option label="特价销售" value="特价销售"></el-option>
            <el-option label="团购销售" value="团购销售"></el-option>
          </el-select>
          <el-button @click="toggleSaleStatus">状态切换 F6</el-button>
        </div>
      </div>

      <div class="customer-info">
        <div class="search-area">
          <div class="search-type">
            <span>手机 Ctrl+Q</span>
            <el-input v-model="searchPhone" placeholder=""></el-input>
          </div>
          <div class="register-btn">
            <span>注册 Ctrl+N</span>
          </div>
        </div>
        <div class="customer-fields">
          <div class="field">
            <span>姓名:</span>
            <el-input v-model="customerName" placeholder=""></el-input>
          </div>
          <div class="field">
            <span>等级积分:</span>
            <el-input v-model="customerPoints" placeholder=""></el-input>
          </div>
        </div>
        <div class="member-options">
          <el-checkbox v-model="useMemberDiscount">使用会员折扣</el-checkbox>
          <span class="member-details">会员详情 ></span>
        </div>
      </div>

      <div class="total-area">
        <div class="payment-title">
          <span>付款</span>
        </div>
        <div class="total-info">
          <div class="total-label">合计:</div>
          <div class="total-value">¥ {{ totalAmount.toFixed(2) }}</div>
        </div>
        <div class="quantity-info">
          <div class="quantity-label">数量:</div>
          <div class="quantity-value">{{ totalQuantity }}</div>
        </div>
        <el-checkbox v-model="autoPromotion">自动执行促销</el-checkbox>
        <el-button type="success" class="checkout-btn" @click="openCheckoutDialog">结算</el-button>
      </div>
    </div>

    <!-- 功能按钮工具栏 -->
    <div class="shortcut-toolbar">
      <el-button size="small" @click="createNewOrder" type="primary">
        开新单 (F2)
      </el-button>
      <el-button size="small" @click="selectSalesPerson">
        营业员 (F3)
      </el-button>
      <el-button size="small" @click="pendingOrder">
        挂单 (F4)
      </el-button>
      <el-button size="small" @click="toggleSaleStatus">
        状态切换 (F6)
      </el-button>
      <el-button size="small" @click="editCurrentQuantity">
        改数量 (F7)
      </el-button>
      <el-button size="small" @click="editCurrentPrice">
        改价格 (F8)
      </el-button>
      <el-button size="small" @click="applyOrderDiscount">
        整单优惠 (F9)
      </el-button>
      <el-button size="small" @click="openPendingOrders">
        处理挂单 (F11)
      </el-button>
      <el-button size="small" @click="focusProductInput">
        商品输入 (F12)
      </el-button>
    </div>

    <!-- 调试工具 -->
    <div class="debug-tools" v-if="showDebugTools">
      <div class="debug-title">快捷键调试</div>
      <div class="debug-buttons">
        <el-button size="small" @click="testKeyEvent('F2')">测试F2</el-button>
        <el-button size="small" @click="testKeyEvent('F3')">测试F3</el-button>
        <el-button size="small" @click="testKeyEvent('F4')">测试F4</el-button>
        <el-button size="small" @click="testKeyEvent('F6')">测试F6</el-button>
        <el-button size="small" @click="testKeyEvent('F7')">测试F7</el-button>
        <el-button size="small" @click="testKeyEvent('F8')">测试F8</el-button>
        <el-button size="small" @click="testKeyEvent('F9')">测试F9</el-button>
        <el-button size="small" @click="testKeyEvent('F11')">测试F11</el-button>
        <el-button size="small" @click="testKeyEvent('F12')">测试F12</el-button>
      </div>
      <div class="debug-log">
        最近事件: {{ lastKeyEvent }}
      </div>
      <div class="debug-toggle">
        <el-button size="small" @click="showDebugTools = false">隐藏调试</el-button>
        <el-button size="small" @click="focusContainer">聚焦容器</el-button>
      </div>
    </div>

    <!-- 系统状态栏 -->
    <div class="status-bar">
      <div class="status-item">系统消息: 欢迎使用云POS!</div>
      <div class="status-actions">
        <span>弹窗 Ctrl+T</span>
        <el-icon><SemiSelect /></el-icon>
        <el-icon><Cherry /></el-icon>
        <el-icon class="shortcut-icon" @click="openShortcutConfig"><Position /></el-icon>
        <el-icon class="shortcut-icon" @click="showDebugTools = true"><MoreFilled /></el-icon>
        <el-icon class="shortcut-help-icon" @click="shortcutHelpVisible = true"><QuestionFilled /></el-icon>
      </div>
    </div>

    <!-- 商品搜索对话框 -->
    <el-dialog v-model="productSearchVisible" title="商品搜索" width="70%">
      <el-input v-model="productSearchKeyword" placeholder="输入商品名称或编码进行搜索" clearable @keyup.enter="performProductSearch">
        <template #append>
          <el-button @click="performProductSearch">搜索</el-button>
        </template>
      </el-input>
      
      <el-table :data="searchResults" style="width: 100%; margin-top: 20px;" height="400" stripe>
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column prop="code" label="商品编码" width="120"></el-table-column>
        <el-table-column prop="name" label="商品名称" width="150"></el-table-column>
        <el-table-column prop="color" label="颜色" width="100"></el-table-column>
        <el-table-column prop="size" label="尺码" width="80"></el-table-column>
        <el-table-column prop="retailPrice" label="零售价" width="100"></el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" @click="addProductToCart(scope.row)" size="small">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 结算支付对话框 -->
    <el-dialog v-model="checkoutDialogVisible" title="订单结算" width="50%">
      <div class="checkout-info">
        <div class="checkout-row">
          <span class="label">应收金额：</span>
          <span class="value">¥ {{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="checkout-row">
          <span class="label">商品数量：</span>
          <span class="value">{{ totalQuantity }} 件</span>
        </div>
        <div class="checkout-row">
          <span class="label">支付方式：</span>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="cash">现金支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="card">银行卡</el-radio>
          </el-radio-group>
        </div>
        <div class="checkout-row" v-if="paymentMethod === 'cash'">
          <span class="label">实付金额：</span>
          <el-input-number v-model="cashPaid" :min="totalAmount" :step="10" :precision="2"></el-input-number>
        </div>
        <div class="checkout-row" v-if="paymentMethod === 'cash' && cashPaid > totalAmount">
          <span class="label">找零：</span>
          <span class="value change-value">¥ {{ (cashPaid - totalAmount).toFixed(2) }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="completeCheckout">完成支付</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 挂单列表对话框 -->
    <el-dialog v-model="pendingOrdersVisible" title="挂单列表" width="70%">
      <el-table :data="pendingOrders" style="width: 100%" height="400" stripe>
        <el-table-column prop="id" label="挂单编号" width="180"></el-table-column>
        <el-table-column prop="time" label="挂单时间" width="180"></el-table-column>
        <el-table-column prop="items" label="商品数量" width="100"></el-table-column>
        <el-table-column prop="amount" label="合计金额" width="120"></el-table-column>
        <el-table-column prop="salesperson" label="营业员" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="recallPendingOrder(scope.row)" size="small">取单</el-button>
            <el-button type="danger" @click="deletePendingOrder(scope.row.id)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pendingOrdersVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 销售人员选择对话框 -->
    <el-dialog v-model="salesPersonDialogVisible" title="选择营业员" width="30%">
      <el-radio-group v-model="selectedSalesPerson">
        <div class="salesperson-list">
          <el-radio v-for="person in salesPersons" :key="person" :label="person">{{ person }}</el-radio>
        </div>
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="salesPersonDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSalesPerson">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 整单折扣对话框 -->
    <el-dialog v-model="discountDialogVisible" title="设置整单折扣" width="30%">
      <div class="discount-options">
        <div class="discount-row">
          <span>折扣率：</span>
          <el-slider v-model="orderDiscount" :min="10" :max="100" :format-tooltip="formatDiscount"></el-slider>
          <span>{{ (orderDiscount / 100).toFixed(2) }}</span>
        </div>
        <div class="discount-row">
          <span>折扣后金额：</span>
          <span class="discount-amount">¥ {{ (totalAmount * orderDiscount / 100).toFixed(2) }}</span>
        </div>
        <div class="discount-row">
          <span>优惠金额：</span>
          <span class="discount-diff">¥ {{ (totalAmount * (1 - orderDiscount / 100)).toFixed(2) }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="discountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="applyDiscount">应用折扣</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 挂单备注对话框 -->
    <el-dialog v-model="pendingRemarkDialogVisible" title="挂单备注" width="30%">
      <el-input
        v-model="pendingRemark"
        type="textarea"
        :rows="3"
        placeholder="请输入挂单备注信息"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pendingRemarkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPendingOrder">确认挂单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 快捷键配置对话框 -->
    <el-dialog v-model="shortcutConfigVisible" title="快捷键配置" width="60%">
      <div class="shortcut-config">
        <div class="shortcut-group">
          <h3>功能按键</h3>
          <div class="shortcut-list">
            <div class="shortcut-item" v-for="(shortcut, key) in functionKeyShortcuts" :key="key">
              <span class="shortcut-name">{{ shortcut.name }}</span>
              <div class="shortcut-keys">
                <el-select v-model="shortcut.key" placeholder="选择按键">
                  <el-option 
                    v-for="option in functionKeyOptions" 
                    :key="option.value" 
                    :label="option.label" 
                    :value="option.value"
                  />
                </el-select>
              </div>
              <div class="shortcut-action">
                <el-button size="small" @click="testShortcut(shortcut)">测试</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="shortcut-group">
          <h3>组合按键</h3>
          <div class="shortcut-list">
            <div class="shortcut-item" v-for="(shortcut, key) in combinationKeyShortcuts" :key="key">
              <span class="shortcut-name">{{ shortcut.name }}</span>
              <div class="shortcut-keys">
                <span class="key-prefix">Ctrl +</span>
                <el-select v-model="shortcut.key" placeholder="选择按键">
                  <el-option 
                    v-for="option in combinationKeyOptions" 
                    :key="option.value" 
                    :label="option.label" 
                    :value="option.value"
                  />
                </el-select>
              </div>
              <div class="shortcut-action">
                <el-button size="small" @click="testShortcut(shortcut)">测试</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetShortcuts">恢复默认</el-button>
          <el-button @click="shortcutConfigVisible = false">取消</el-button>
          <el-button type="primary" @click="saveShortcuts">保存配置</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 快捷键帮助对话框 -->
    <el-dialog v-model="shortcutHelpVisible" title="快捷键帮助" width="60%" class="shortcut-help-dialog">
      <div class="shortcut-help-content">
        <h3>功能键快捷键</h3>
        <div class="shortcut-help-grid">
          <div class="shortcut-help-item" v-for="(shortcut, key) in functionKeyShortcuts" :key="`func-${key}`">
            <div class="key-badge">{{ shortcut.key }}</div>
            <div class="key-name">{{ shortcut.name }}</div>
          </div>
        </div>

        <h3>组合键快捷键 (Ctrl+键)</h3>
        <div class="shortcut-help-grid">
          <div class="shortcut-help-item" v-for="(shortcut, key) in combinationKeyShortcuts" :key="`combo-${key}`">
            <div class="key-badge combo">Ctrl+{{ shortcut.key.toUpperCase() }}</div>
            <div class="key-name">{{ shortcut.name }}</div>
          </div>
        </div>

        <div class="shortcut-help-tips">
          <h3>使用提示</h3>
          <ul>
            <li>请确保收银窗口处于聚焦状态</li>
            <li>点击窗口空白处可以使窗口聚焦</li>
            <li>如果快捷键无效，可以尝试点击"聚焦容器"按钮</li>
            <li>输入状态下，功能键仍然可用</li>
            <li>可以在右下角的设置图标中自定义快捷键</li>
          </ul>
        </div>

        <div class="shortcut-help-footer">
          <el-button @click="focusContainer" type="primary">聚焦容器</el-button>
          <el-button @click="showDebugTools = true">打开调试工具</el-button>
          <el-button @click="shortcutHelpVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 快捷键状态指示器 -->
    <div class="shortcut-indicator" v-if="lastKeyEvent" :class="{ 'active': lastKeyEventTime > 0 }">
      <div class="indicator-content">
        <div class="indicator-key">{{ lastKeyEvent }}</div>
        <div class="indicator-action">{{ getActionForKey(lastKeyEvent) }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  CircleCheck, Monitor, Right, Plus, Avatar, Files, 
  EditPen, Discount, Ticket, SetUp, DataAnalysis,
  SemiSelect, Cherry, Position, QuestionFilled,
  MoreFilled
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
// 定义特殊布局，不使用默认布局
definePageMeta({
  layout: false
})
// 表单数据
const retailType = ref('正常零售')
const salesPerson = ref('申申')
const memberNumber = ref('')
const searchPhone = ref('')
const customerName = ref('')
const customerPoints = ref('')
const useMemberDiscount = ref(false)
const saleTypeValue = ref('正常零售')
const autoPromotion = ref(true)
const productCodeInput = ref('')
const productInputRef = ref(null)
const productSearchVisible = ref(false)
const productSearchKeyword = ref('')
const searchResults = ref([])
const checkoutDialogVisible = ref(false)
const paymentMethod = ref('cash')
const cashPaid = ref(0)

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: '52082151',
    name: '女装休闲鞋',
    color: '[613]粉紫',
    size: '[36]230',
    retailPrice: 219.00,
    discount: 0.63,
    actualPrice: 139.00,
    quantity: 1,
    actualAmount: 139.00,
    totalAmount: 139.00,
    salesperson: '申申',
    saleType: '正常零售',
    unique: ''
  },
  {
    id: 2,
    code: '52098086',
    name: '女装注塑鞋',
    color: '[705]米灰',
    size: '[36]230',
    retailPrice: 185.00,
    discount: 0.70,
    actualPrice: 129.00,
    quantity: 1,
    actualAmount: 129.00,
    totalAmount: 129.00,
    salesperson: '申申',
    saleType: '正常零售',
    unique: ''
  },
  {
    id: 3,
    code: '5X55585L',
    name: '儿童凉鞋',
    color: '[701]灰色',
    size: '[34]220',
    retailPrice: 219.00,
    discount: 0.63,
    actualPrice: 139.00,
    quantity: 1,
    actualAmount: 139.00,
    totalAmount: 139.00,
    salesperson: '申申',
    saleType: '正常零售',
    unique: ''
  }
])

// 商品数据库（模拟数据）
const productDatabase = ref([
  {
    id: 1,
    code: '52082151',
    name: '女装休闲鞋',
    color: '[613]粉紫',
    size: '[36]230',
    retailPrice: 219.00,
    discount: 0.63,
    actualPrice: 139.00,
    stock: 10
  },
  {
    id: 2,
    code: '52098086',
    name: '女装注塑鞋',
    color: '[705]米灰',
    size: '[36]230',
    retailPrice: 185.00,
    discount: 0.70,
    actualPrice: 129.00,
    stock: 8
  },
  {
    id: 3,
    code: '5X55585L',
    name: '儿童凉鞋',
    color: '[701]灰色',
    size: '[34]220',
    retailPrice: 219.00,
    discount: 0.63,
    actualPrice: 139.00,
    stock: 15
  },
  {
    id: 4,
    code: '60982135',
    name: '男士商务鞋',
    color: '[101]黑色',
    size: '[42]260',
    retailPrice: 299.00,
    discount: 0.80,
    actualPrice: 239.00,
    stock: 5
  },
  {
    id: 5,
    code: '61008276',
    name: '女士高跟鞋',
    color: '[201]红色',
    size: '[37]235',
    retailPrice: 259.00,
    discount: 0.70,
    actualPrice: 181.00,
    stock: 12
  },
  {
    id: 6,
    code: '61298341',
    name: '儿童运动鞋',
    color: '[501]蓝色',
    size: '[30]190',
    retailPrice: 169.00,
    discount: 0.65,
    actualPrice: 109.00,
    stock: 20
  }
])

// 选中的行
const selectedRows = ref([])

// 计算属性
const totalAmount = computed(() => {
  return tableData.value.reduce((total, item) => total + item.totalAmount, 0)
})

const totalQuantity = computed(() => {
  return tableData.value.reduce((total, item) => total + item.quantity, 0)
})

// 快捷键配置相关
const shortcutConfigVisible = ref(false)

// 功能键选项
const functionKeyOptions = [
  { value: 'F1', label: 'F1' },
  { value: 'F2', label: 'F2' },
  { value: 'F3', label: 'F3' },
  { value: 'F4', label: 'F4' },
  { value: 'F5', label: 'F5' },
  { value: 'F6', label: 'F6' },
  { value: 'F7', label: 'F7' },
  { value: 'F8', label: 'F8' },
  { value: 'F9', label: 'F9' },
  { value: 'F10', label: 'F10' },
  { value: 'F11', label: 'F11' },
  { value: 'F12', label: 'F12' }
]

// 组合键选项
const combinationKeyOptions = [
  { value: 'a', label: 'A' },
  { value: 'b', label: 'B' },
  { value: 'c', label: 'C' },
  { value: 'd', label: 'D' },
  { value: 'e', label: 'E' },
  { value: 'f', label: 'F' },
  { value: 'g', label: 'G' },
  { value: 'h', label: 'H' },
  { value: 'i', label: 'I' },
  { value: 'j', label: 'J' },
  { value: 'k', label: 'K' },
  { value: 'l', label: 'L' },
  { value: 'm', label: 'M' },
  { value: 'n', label: 'N' },
  { value: 'o', label: 'O' },
  { value: 'p', label: 'P' },
  { value: 'q', label: 'Q' },
  { value: 'r', label: 'R' },
  { value: 's', label: 'S' },
  { value: 't', label: 'T' },
  { value: 'u', label: 'U' },
  { value: 'v', label: 'V' },
  { value: 'w', label: 'W' },
  { value: 'x', label: 'X' },
  { value: 'y', label: 'Y' },
  { value: 'z', label: 'Z' }
]

// 存储快捷键映射，用于快速查找
const keyToActionMap = reactive({})

// 先定义函数声明，这样就可以在默认快捷键配置中引用
// 创建新订单
const createNewOrder = () => {
  if (tableData.value.length === 0) {
    ElMessage.info('当前已是新订单')
    return
  }
  
  ElMessageBox.confirm(
    '确定要清空当前订单并创建新订单吗？',
    '开新单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    tableData.value = []
    ElMessage.success('已创建新订单')
    
    // 重置输入框
    productCodeInput.value = ''
    nextTick(() => {
      productInputRef.value && productInputRef.value.focus()
    })
  }).catch(() => {
    // 取消操作
  })
}

// 选择营业员
const selectSalesPerson = () => {
  selectedSalesPerson.value = salesPerson.value
  salesPersonDialogVisible.value = true
}

// 挂单
const pendingOrder = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('购物车为空，无法挂单')
    return
  }
  
  pendingRemark.value = ''
  pendingRemarkDialogVisible.value = true
}

// 切换销售状态
const toggleSaleStatus = () => {
  if (saleTypeValue.value === '正常零售') {
    saleTypeValue.value = '会员零售'
  } else if (saleTypeValue.value === '会员零售') {
    saleTypeValue.value = '特价销售'
  } else if (saleTypeValue.value === '特价销售') {
    saleTypeValue.value = '团购销售'
  } else {
    saleTypeValue.value = '正常零售'
  }
  
  // 更新所有商品的销售类型
  tableData.value.forEach(item => {
    item.saleType = saleTypeValue.value
  })
  
  ElMessage.success(`销售类型已切换为: ${saleTypeValue.value}`)
}

// 修改所选商品数量
const editCurrentQuantity = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要修改的商品')
    return
  }
  
  if (selectedRows.value.length > 1) {
    ElMessage.warning('一次只能修改一个商品的数量')
    return
  }
  
  const product = selectedRows.value[0]
  
  ElMessageBox.prompt(
    '请输入新的数量:',
    '修改数量',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: product.quantity,
      inputValidator: (value) => {
        const num = parseInt(value)
        return num > 0 && num < 100
      },
      inputErrorMessage: '数量必须在1-99之间'
    }
  ).then(({ value }) => {
    const newQuantity = parseInt(value)
    product.quantity = newQuantity
    product.totalAmount = product.actualAmount * newQuantity
    ElMessage.success(`商品"${product.name}"数量已更新为${newQuantity}`)
  }).catch(() => {
    // 取消操作
  })
}

// 修改所选商品价格
const editCurrentPrice = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要修改的商品')
    return
  }
  
  if (selectedRows.value.length > 1) {
    ElMessage.warning('一次只能修改一个商品的价格')
    return
  }
  
  const product = selectedRows.value[0]
  
  ElMessageBox.prompt(
    '请输入新的价格:',
    '修改价格',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: product.actualAmount,
      inputValidator: (value) => {
        const num = parseFloat(value)
        return num > 0
      },
      inputErrorMessage: '价格必须大于0'
    }
  ).then(({ value }) => {
    const newPrice = parseFloat(value)
    product.discount = (newPrice / product.retailPrice).toFixed(2)
    product.actualAmount = newPrice
    product.actualPrice = newPrice
    product.totalAmount = newPrice * product.quantity
    ElMessage.success(`商品"${product.name}"价格已更新为¥${newPrice}`)
  }).catch(() => {
    // 取消操作
  })
}

// 整单优惠
const applyOrderDiscount = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('购物车为空，无法应用折扣')
    return
  }
  
  orderDiscount.value = 100 // 重置为不打折
  discountDialogVisible.value = true
}

// 打开挂单列表
const openPendingOrders = () => {
  pendingOrdersVisible.value = true
}

// 取回挂单
const recallPendingOrder = (order) => {
  if (tableData.value.length > 0) {
    ElMessageBox.confirm(
      '当前购物车中已有商品，确定要清空并取回挂单吗？',
      '取回挂单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      tableData.value = order.orderData
      pendingOrders.value = pendingOrders.value.filter(o => o.id !== order.id)
      pendingOrdersVisible.value = false
      ElMessage.success('已取回挂单')
    }).catch(() => {
      // 取消操作
    })
  } else {
    tableData.value = order.orderData
    pendingOrders.value = pendingOrders.value.filter(o => o.id !== order.id)
    pendingOrdersVisible.value = false
    ElMessage.success('已取回挂单')
  }
}

// 删除挂单
const deletePendingOrder = (id) => {
  ElMessageBox.confirm(
    '确定要删除该挂单吗？',
    '删除挂单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    pendingOrders.value = pendingOrders.value.filter(o => o.id !== id)
    ElMessage.success('挂单已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已更新')
}

// 移动焦点到商品输入框
const focusProductInput = () => {
  nextTick(() => {
    productInputRef.value && productInputRef.value.focus()
  })
}

// 聚焦到手机搜索框
const focusPhoneInput = () => {
  nextTick(() => {
    const phoneInput = document.querySelector('.search-type input')
    phoneInput && phoneInput.focus()
  })
}

// 会员注册功能
const showMemberRegister = () => {
  ElMessage.info('会员注册功能')
}

// 弹窗功能
const showPopup = () => {
  ElMessage.info('弹窗功能')
}

// 默认快捷键配置
const defaultFunctionKeyShortcuts = {
  newOrder: { name: '开新单', key: 'F2', action: createNewOrder },
  salesperson: { name: '营业员', key: 'F3', action: selectSalesPerson },
  pendingOrder: { name: '挂单', key: 'F4', action: pendingOrder },
  statusToggle: { name: '状态切换', key: 'F6', action: toggleSaleStatus },
  editQuantity: { name: '改数量', key: 'F7', action: editCurrentQuantity },
  editPrice: { name: '改价格', key: 'F8', action: editCurrentPrice },
  orderDiscount: { name: '整单优惠', key: 'F9', action: applyOrderDiscount },
  processPending: { name: '处理挂单', key: 'F11', action: openPendingOrders },
  productInput: { name: '商品输入', key: 'F12', action: focusProductInput }
}

const defaultCombinationKeyShortcuts = {
  phoneSearch: { name: '手机搜索', key: 'q', action: focusPhoneInput },
  register: { name: '会员注册', key: 'n', action: showMemberRegister },
  refreshData: { name: '更新数据', key: 'r', action: refreshData },
  popup: { name: '弹窗', key: 't', action: showPopup }
}

// 使用深拷贝创建实际使用的快捷键配置（可修改）
const functionKeyShortcuts = reactive(JSON.parse(JSON.stringify(defaultFunctionKeyShortcuts)))
const combinationKeyShortcuts = reactive(JSON.parse(JSON.stringify(defaultCombinationKeyShortcuts)))

// 更新快捷键映射
const updateKeyMap = () => {
  // 清空当前映射
  Object.keys(keyToActionMap).forEach(key => delete keyToActionMap[key])
  
  // 添加功能键映射
  Object.values(functionKeyShortcuts).forEach(shortcut => {
    keyToActionMap[shortcut.key] = shortcut.action
  })
  
  // 添加组合键映射
  Object.values(combinationKeyShortcuts).forEach(shortcut => {
    keyToActionMap[`Ctrl+${shortcut.key}`] = shortcut.action
  })
}

// 打开快捷键配置
const openShortcutConfig = () => {
  shortcutConfigVisible.value = true
}

// 重置为默认快捷键
const resetShortcuts = () => {
  Object.keys(functionKeyShortcuts).forEach(key => {
    functionKeyShortcuts[key].key = defaultFunctionKeyShortcuts[key].key
  })
  
  Object.keys(combinationKeyShortcuts).forEach(key => {
    combinationKeyShortcuts[key].key = defaultCombinationKeyShortcuts[key].key
  })
  
  ElMessage.success('已恢复默认快捷键配置')
}

// 保存快捷键配置
const saveShortcuts = () => {
  // 检查功能键是否有重复
  const functionKeys = Object.values(functionKeyShortcuts).map(s => s.key)
  const combinationKeys = Object.values(combinationKeyShortcuts).map(s => s.key)
  
  if (new Set(functionKeys).size !== functionKeys.length) {
    ElMessage.error('功能键存在重复，请修改后再保存')
    return
  }
  
  if (new Set(combinationKeys).size !== combinationKeys.length) {
    ElMessage.error('组合键存在重复，请修改后再保存')
    return
  }
  
  // 更新快捷键映射
  updateKeyMap()
  
  // 保存到本地存储
  const functionKeysToSave = {}
  Object.keys(functionKeyShortcuts).forEach(key => {
    functionKeysToSave[key] = functionKeyShortcuts[key].key
  })
  
  const combinationKeysToSave = {}
  Object.keys(combinationKeyShortcuts).forEach(key => {
    combinationKeysToSave[key] = combinationKeyShortcuts[key].key
  })
  
  localStorage.setItem('posSystemFunctionKeys', JSON.stringify(functionKeysToSave))
  localStorage.setItem('posSystemCombinationKeys', JSON.stringify(combinationKeysToSave))
  
  shortcutConfigVisible.value = false
  ElMessage.success('快捷键配置已保存')
}

// 测试快捷键
const testShortcut = (shortcut) => {
  ElMessage.success(`正在测试快捷键: ${shortcut.name}`)
  shortcut.action()
}

// 确认营业员选择
const confirmSalesPerson = () => {
  salesPerson.value = selectedSalesPerson.value
  
  // 更新所有商品的营业员
  tableData.value.forEach(item => {
    item.salesperson = salesPerson.value
  })
  
  salesPersonDialogVisible.value = false
  ElMessage.success(`营业员已更改为: ${salesPerson.value}`)
}

// 确认挂单
const confirmPendingOrder = () => {
  const date = new Date()
  const pendingId = `P${date.getTime()}`
  const formattedTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${date.toLocaleTimeString()}`
  
  // 保存当前订单
  pendingOrders.value.push({
    id: pendingId,
    time: formattedTime,
    items: totalQuantity.value,
    amount: totalAmount.value.toFixed(2),
    salesperson: salesPerson.value,
    remark: pendingRemark.value,
    orderData: JSON.parse(JSON.stringify(tableData.value)) // 深拷贝
  })
  
  pendingRemarkDialogVisible.value = false
  tableData.value = []
  ElMessage.success('订单已挂起')
  
  // 重置输入框
  productCodeInput.value = ''
  nextTick(() => {
    productInputRef.value && productInputRef.value.focus()
  })
}

// 调试工具相关
const showDebugTools = ref(false)
const lastKeyEvent = ref('')
const posContainerRef = ref(null)
const testKeyEvent = (key) => {
  lastKeyEvent.value = key
  handleKeyDown({ key, preventDefault: () => {} })
}
const focusContainer = () => {
  nextTick(() => {
    posContainerRef.value && posContainerRef.value.focus()
  })
}

// 容器级键盘事件
const containerKeyDown = (event) => {
  console.log('容器键盘事件:', event.key)
  lastKeyEvent.value = `容器:${event.ctrlKey ? 'Ctrl+' : ''}${event.key}`
  
  // 使用相同的处理逻辑，避免代码重复
  const handled = handleKeyDown(event)
  
  // 如果事件已处理，阻止默认行为和冒泡
  if (handled) {
    event.preventDefault()
    event.stopPropagation()
  }
}

// 生命周期钩子
onMounted(() => {
  console.log('组件已挂载，添加键盘事件监听')
  
  // 挂载后自动聚焦容器元素，以便捕获按键事件
  nextTick(() => {
    // 确保容器得到焦点，从而能响应键盘事件
    posContainerRef.value && posContainerRef.value.focus()
    productInputRef.value && productInputRef.value.focus()
  })
  
  // 更新键盘映射
  updateKeyMap()
  console.log('键盘映射已更新:', keyToActionMap)
  
  // 使用捕获阶段监听按键事件，确保能在其他元素之前处理
  document.addEventListener('keydown', handleKeyDown, true)
  
  // 设置定时器，每隔一段时间自动聚焦容器元素
  const focusInterval = setInterval(() => {
    if (document.activeElement.tagName !== 'INPUT' && 
        document.activeElement.tagName !== 'TEXTAREA' &&
        !shortcutConfigVisible.value && 
        !pendingOrdersVisible.value && 
        !salesPersonDialogVisible.value && 
        !discountDialogVisible.value && 
        !pendingRemarkDialogVisible.value && 
        !checkoutDialogVisible.value &&
        !productSearchVisible.value) {
      posContainerRef.value && posContainerRef.value.focus()
    }
  }, 5000) // 每5秒检查一次
  
  // 创建全局函数，可以在浏览器控制台中测试
  window.posTestF2 = createNewOrder
  window.posTestF3 = selectSalesPerson
  window.posTestF4 = pendingOrder
  window.posTestF6 = toggleSaleStatus
  window.posTestF7 = editCurrentQuantity
  window.posTestF8 = editCurrentPrice
  window.posTestF9 = applyOrderDiscount
  window.posTestF11 = openPendingOrders
  window.posTestF12 = focusProductInput
  
  // 尝试从本地存储加载自定义快捷键
  const savedFunctionKeys = localStorage.getItem('posSystemFunctionKeys')
  const savedCombinationKeys = localStorage.getItem('posSystemCombinationKeys')
  
  if (savedFunctionKeys) {
    try {
      const parsed = JSON.parse(savedFunctionKeys)
      Object.keys(parsed).forEach(key => {
        if (functionKeyShortcuts[key]) {
          functionKeyShortcuts[key].key = parsed[key]
        }
      })
    } catch (e) {
      console.error('快捷键配置加载失败', e)
    }
  }
  
  if (savedCombinationKeys) {
    try {
      const parsed = JSON.parse(savedCombinationKeys)
      Object.keys(parsed).forEach(key => {
        if (combinationKeyShortcuts[key]) {
          combinationKeyShortcuts[key].key = parsed[key]
        }
      })
    } catch (e) {
      console.error('快捷键配置加载失败', e)
    }
  }
  
  // 再次更新映射以应用从本地存储加载的配置
  updateKeyMap()
  
  // 在控制台中打印使用说明
  console.info('可在控制台中使用 posTestF2(), posTestF3()... 等测试快捷键功能')
  
  // 显示快捷键使用提示
  setTimeout(() => {
    ElMessage({
      message: '按 F12 聚焦商品输入框，按问号图标查看所有快捷键',
      type: 'info',
      duration: 5000
    })
  }, 1000)
  
  // 保存清除间隔的引用，以便在卸载组件时清除
  return () => {
    clearInterval(focusInterval)
  }
})

onUnmounted(() => {
  console.log('组件卸载，移除键盘事件监听')
  // 组件卸载时移除事件监听
  document.removeEventListener('keydown', handleKeyDown, true)
  
  // 移除全局函数
  delete window.posTestF2
  delete window.posTestF3
  delete window.posTestF4
  delete window.posTestF6
  delete window.posTestF7
  delete window.posTestF8
  delete window.posTestF9
  delete window.posTestF11
  delete window.posTestF12
})

// 跟踪最后键盘事件的时间
const lastKeyEventTime = ref(0)

// 根据按键获取对应的操作名称
const getActionForKey = (key) => {
  if (!key) return ''
  
  // 处理功能键
  for (const shortcutKey in functionKeyShortcuts) {
    const shortcut = functionKeyShortcuts[shortcutKey]
    if (key === shortcut.key) {
      return shortcut.name
    }
  }
  
  // 处理组合键
  if (key.startsWith('Ctrl+')) {
    const baseKey = key.replace('Ctrl+', '').toLowerCase()
    for (const shortcutKey in combinationKeyShortcuts) {
      const shortcut = combinationKeyShortcuts[shortcutKey]
      if (baseKey === shortcut.key.toLowerCase()) {
        return shortcut.name
      }
    }
  }
  
  return '未知操作'
}

// 重写键盘事件处理，以更新指示器
const handleKeyDown = (event) => {
  const keyName = `${event.ctrlKey ? 'Ctrl+' : ''}${event.key}`
  console.log('键盘事件触发:', keyName)
  lastKeyEvent.value = keyName
  lastKeyEventTime.value = Date.now()
  
  // 2秒后隐藏指示器
  setTimeout(() => {
    if (Date.now() - lastKeyEventTime.value >= 1900) {
      lastKeyEventTime.value = 0
    }
  }, 2000)
  
  // 避免在输入框中触发快捷键
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    // 但是允许回车键在商品编码输入框中工作
    if (event.key === 'Enter' && event.target === productInputRef.value?.$el.querySelector('input')) {
      searchProduct()
    }
    return
  }
  
  // 检查是否是对话框打开状态，如果是则不处理快捷键
  if (shortcutConfigVisible.value || 
      pendingOrdersVisible.value || 
      salesPersonDialogVisible.value || 
      discountDialogVisible.value || 
      pendingRemarkDialogVisible.value || 
      checkoutDialogVisible.value ||
      productSearchVisible.value) {
    return
  }
  
  // 直接处理具体的快捷键，不再使用映射
  switch (event.key) {
    case 'F2':
      event.preventDefault()
      createNewOrder()
      return true
    case 'F3':
      event.preventDefault()
      selectSalesPerson()
      return true
    case 'F4':
      event.preventDefault()
      pendingOrder()
      return true
    case 'F6':
      event.preventDefault()
      toggleSaleStatus()
      return true
    case 'F7':
      event.preventDefault()
      editCurrentQuantity()
      return true
    case 'F8':
      event.preventDefault()
      editCurrentPrice()
      return true
    case 'F9':
      event.preventDefault()
      applyOrderDiscount()
      return true
    case 'F11':
      event.preventDefault()
      openPendingOrders()
      return true
    case 'F12':
      event.preventDefault()
      focusProductInput()
      return true
  }
  
  // 处理组合键
  if (event.ctrlKey) {
    switch (event.key.toLowerCase()) {
      case 'q':
        event.preventDefault()
        focusPhoneInput()
        return true
      case 'n':
        event.preventDefault()
        showMemberRegister()
        return true
      case 'r':
        event.preventDefault()
        refreshData()
        return true
      case 't':
        event.preventDefault()
        showPopup()
        return true
    }
  }
  
  return false
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 搜索商品
const searchProduct = () => {
  if (!productCodeInput.value) {
    productSearchVisible.value = true
    return
  }
  
  const foundProduct = productDatabase.value.find(p => p.code === productCodeInput.value)
  
  if (foundProduct) {
    addProductToCart(foundProduct)
    productCodeInput.value = ''
  } else {
    ElMessage.warning('商品编码不存在，已打开商品搜索')
    productSearchVisible.value = true
    productSearchKeyword.value = productCodeInput.value
    performProductSearch()
  }
}

// 执行商品搜索
const performProductSearch = () => {
  if (!productSearchKeyword.value) {
    searchResults.value = [...productDatabase.value]
    return
  }
  
  const keyword = productSearchKeyword.value.toLowerCase()
  searchResults.value = productDatabase.value.filter(p => 
    p.code.toLowerCase().includes(keyword) || 
    p.name.toLowerCase().includes(keyword)
  )
}

// 添加商品到购物车
const addProductToCart = (product) => {
  // 检查商品是否已在购物车中
  const existingProduct = tableData.value.find(p => p.code === product.code)
  
  if (existingProduct) {
    // 如果已存在，增加数量
    existingProduct.quantity++
    existingProduct.totalAmount = existingProduct.actualAmount * existingProduct.quantity
    ElMessage.success('商品数量已增加')
  } else {
    // 生成新的商品行
    const newProduct = {
      id: tableData.value.length > 0 ? Math.max(...tableData.value.map(p => p.id)) + 1 : 1,
      code: product.code,
      name: product.name,
      color: product.color,
      size: product.size,
      retailPrice: product.retailPrice,
      discount: product.discount,
      actualPrice: product.actualPrice,
      quantity: 1,
      actualAmount: product.actualPrice,
      totalAmount: product.actualPrice,
      salesperson: salesPerson.value,
      saleType: saleTypeValue.value,
      unique: ''
    }
    
    // 添加到表格
    tableData.value.push(newProduct)
    ElMessage.success('商品已添加')
  }
  
  // 如果是从搜索框添加，关闭搜索框
  productSearchVisible.value = false
  productSearchKeyword.value = ''
  
  // 更新焦点
  nextTick(() => {
    productInputRef.value && productInputRef.value.focus()
  })
}

// 更改数量
const handleQuantityChange = (row, value) => {
  // 更新总金额
  row.totalAmount = row.actualAmount * value
  ElMessage.success(`商品"${row.name}"数量已更新`)
}

// 从购物车中移除商品
const removeProduct = (product) => {
  ElMessageBox.confirm(
    `确定要删除商品"${product.name}"吗？`,
    '删除商品',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    tableData.value = tableData.value.filter(p => p.id !== product.id)
    ElMessage.success('商品已从购物车中移除')
  }).catch(() => {
    // 取消操作
  })
}

// 打开结算对话框
const openCheckoutDialog = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算')
    return
  }
  
  checkoutDialogVisible.value = true
  cashPaid.value = Math.ceil(totalAmount.value / 10) * 10 // 向上取整到最接近的10的倍数
}

// 完成结算
const completeCheckout = () => {
  ElMessage.success('订单支付成功！')
  checkoutDialogVisible.value = false
  
  // 生成新的订单号
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  const newOrderId = `${year}${month}${day}PM${random}`
  
  // 清空购物车，准备新订单
  tableData.value = []
  
  // 消息提示
  ElMessageBox.alert(
    `订单号: ${newOrderId}<br>金额: ¥${totalAmount.value.toFixed(2)}<br>支付方式: ${getPaymentMethodText()}<br>时间: ${year}-${month}-${day} ${new Date().toLocaleTimeString()}`,
    '订单支付成功',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      callback: () => {
        // 将焦点放回到商品输入框
        nextTick(() => {
          productInputRef.value && productInputRef.value.focus()
        })
      }
    }
  )
}

// 获取支付方式的文本描述
const getPaymentMethodText = () => {
  switch(paymentMethod.value) {
    case 'cash': return '现金支付'
    case 'alipay': return '支付宝'
    case 'wechat': return '微信支付'
    case 'card': return '银行卡'
    default: return ''
  }
}

// 挂单相关
const pendingOrdersVisible = ref(false)
const pendingOrders = ref([])
const pendingRemarkDialogVisible = ref(false)
const pendingRemark = ref('')

// 销售人员对话框
const salesPersonDialogVisible = ref(false)
const selectedSalesPerson = ref('申申')
const salesPersons = ref(['申申', '张三', '李四', '王五', '赵六'])

// 折扣对话框
const discountDialogVisible = ref(false)
const orderDiscount = ref(100) // 100% 不打折

// 格式化折扣提示
const formatDiscount = (val) => {
  return `${(val / 100).toFixed(2)}折`
}

// 应用整单折扣
const applyDiscount = () => {
  if (orderDiscount.value === 100) {
    discountDialogVisible.value = false
    return
  }
  
  const discountRatio = orderDiscount.value / 100
  
  // 更新所有商品的价格
  tableData.value.forEach(item => {
    const originalPrice = item.retailPrice
    const newPrice = (originalPrice * discountRatio).toFixed(2)
    item.discount = discountRatio.toFixed(2)
    item.actualPrice = parseFloat(newPrice)
    item.actualAmount = parseFloat(newPrice)
    item.totalAmount = item.quantity * parseFloat(newPrice)
  })
  
  discountDialogVisible.value = false
  ElMessage.success(`已应用${(orderDiscount.value / 10).toFixed(1)}折优惠`)
}

// 添加快捷键帮助对话框状态
const shortcutHelpVisible = ref(false)

// 获取路由器实例
const router = useRouter()

// 页面导航
const navigateTo = (path) => {
  router.push(path)
}

// 显示功能建设中提示
const showUnderConstruction = (feature) => {
  ElMessageBox.alert(
    `${feature}功能正在建设中，敬请期待!`,
    '功能开发中',
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  )
}
</script>

<style scoped lang="scss">
.pos-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  color: #333;
  font-family: Arial, sans-serif;
}

.pos-header {
  display: flex;
  align-items: center;
  background-color: #1e4b9a;
  color: white;
  padding: 0.5rem 1rem;
  height: 60px;

  .logo {
    font-size: 1.2rem;
    font-weight: bold;
    margin-right: 1rem;
  }

  .store-info {
    flex: 1;
    .store-code {
      background-color: white;
      color: #333;
      padding: 0 0.5rem;
      border-radius: 4px;
      margin-left: 0.5rem;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;

    .header-icons {
      display: flex;
      gap: 0.5rem;
      margin-left: 1rem;
    }
  }
}

.order-info {
  padding: 0.5rem;
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;

  .order-details {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    align-items: center;

    .order-item {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
  }
}

.goods-table {
  flex: 1;
  padding: 0.5rem;
  background-color: #fff;
  overflow: hidden;
}

.pos-footer {
  display: flex;
  padding: 1rem;
  background-color: #ebeef5;
  
  .input-area {
    width: 25%;
    padding: 0.5rem;
    background-color: #f2f6fc;
    border-radius: 4px;

    .input-prompt {
      margin-bottom: 1rem;

      .product-input {
        background: white;
      }
    }

    .sale-type {
      display: flex;
      gap: 0.5rem;
      align-items: center;
    }
  }

  .customer-info {
    flex: 1;
    padding: 0.5rem 1rem;
    
    .search-area {
      display: flex;
      gap: 1rem;
      margin-bottom: 1rem;

      .search-type {
        display: flex;
        flex-direction: column;
        flex: 1;
      }

      .register-btn {
        padding: 1rem;
        display: flex;
        align-items: center;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }
    }

    .customer-fields {
      display: flex;
      gap: 1rem;
      margin-bottom: 1rem;

      .field {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        flex: 1;
      }
    }

    .member-options {
      display: flex;
      justify-content: space-between;
      
      .member-details {
        color: #409EFF;
        cursor: pointer;
      }
    }
  }

  .total-area {
    width: 20%;
    padding: 0.5rem;
    background-color: #1e4b9a;
    color: white;
    border-radius: 4px;
    display: flex;
    flex-direction: column;

    .payment-title {
      text-align: center;
      margin-bottom: 1rem;
      font-weight: bold;
    }

    .total-info, .quantity-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0.5rem;
      font-size: 1.2rem;
    }

    .total-value {
      font-size: 1.5rem;
      font-weight: bold;
    }

    :deep(.el-checkbox__label) {
      color: white;
    }

    .checkout-btn {
      margin-top: 1rem;
      font-size: 1.1rem;
      height: 40px;
    }
  }
}

.function-buttons {
  display: flex;
  justify-content: space-around;
  padding: 1rem;
  background-color: #fff;
  border-top: 1px solid #dcdfe6;

  .function-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;

    .function-name {
      margin: 0.3rem 0;
    }

    .function-key {
      font-size: 0.8rem;
      color: #909399;
    }
  }
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: #f2f6fc;
  border-top: 1px solid #dcdfe6;
  font-size: 0.9rem;
  
  .status-actions {
    display: flex;
    align-items: center;
    gap: 1rem;
    
    .shortcut-icon {
      cursor: pointer;
      &:hover {
        color: #409EFF;
      }
    }
  }
}

// 促销标签样式
.promotion-tag {
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  margin-bottom: 2px;
  font-size: 0.85rem;
  
  &.new {
    background-color: #ecf5ff;
    color: #409EFF;
    border: 1px solid #d9ecff;
  }
  
  &.store {
    background-color: #f0f9eb;
    color: #67c23a;
    border: 1px solid #e1f3d8;
  }
}

.promo-date {
  font-size: 0.75rem;
  color: #909399;
}

:deep(.el-table__row.selected-row) {
  background-color: #f0f9eb;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

// 结算对话框样式
.checkout-info {
  padding: 15px;
  
  .checkout-row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .label {
      width: 100px;
      text-align: right;
      padding-right: 15px;
      font-weight: bold;
    }
    
    .value {
      font-size: 1.2rem;
      
      &.change-value {
        color: #67c23a;
        font-weight: bold;
      }
    }
  }
}

// 对话框按钮
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

// 重写Element Plus的一些样式
:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

// 销售人员列表样式
.salesperson-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px;
}

// 折扣对话框样式
.discount-options {
  .discount-row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .el-slider {
      flex: 1;
      margin: 0 15px;
    }
    
    .discount-amount, .discount-diff {
      font-size: 1.2rem;
      font-weight: bold;
    }
    
    .discount-diff {
      color: #f56c6c;
    }
  }
}

// 快捷键配置样式
.shortcut-config {
  .shortcut-group {
    margin-bottom: 20px;
    
    h3 {
      margin: 0 0 15px 0;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .shortcut-list {
      .shortcut-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        
        .shortcut-name {
          width: 100px;
          font-weight: bold;
        }
        
        .shortcut-keys {
          flex: 1;
          display: flex;
          align-items: center;
          
          .key-prefix {
            margin-right: 10px;
            font-weight: bold;
          }
        }
        
        .shortcut-action {
          margin-left: 15px;
        }
      }
    }
  }
}

.shortcut-toolbar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0.5rem 1rem;
  background-color: #fff;
  border-top: 1px solid #dcdfe6;
  gap: 0.5rem;
  
  .el-button {
    flex: 1;
    min-width: 100px;
  }
}

// 调试工具样式
.debug-tools {
  padding: 1rem;
  background-color: #fff;
  border-top: 1px solid #dcdfe6;

  .debug-title {
    font-size: 1.2rem;
    font-weight: bold;
    margin-bottom: 1rem;
  }

  .debug-buttons {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
  }

  .debug-log {
    margin-bottom: 1rem;
  }

  .debug-toggle {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
  }
}

/* 快捷键帮助样式 */
.shortcut-help-icon {
  cursor: pointer;
  font-size: 20px;
  color: #409EFF;
}

.shortcut-help-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-bottom: 25px;
}

.shortcut-help-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.key-badge {
  padding: 4px 8px;
  background-color: #409EFF;
  color: white;
  border-radius: 4px;
  font-weight: bold;
  min-width: 40px;
  text-align: center;
}

.key-badge.combo {
  background-color: #67C23A;
}

.key-name {
  font-weight: 500;
}

.shortcut-help-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-left: 4px solid #67C23A;
  border-radius: 4px;
}

.shortcut-help-tips ul {
  padding-left: 20px;
}

.shortcut-help-tips li {
  margin-bottom: 8px;
}

.shortcut-help-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 快捷键状态指示器 */
.shortcut-indicator {
  position: fixed;
  bottom: 70px;
  right: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  z-index: 9999;
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.3s, transform 0.3s;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.shortcut-indicator.active {
  opacity: 1;
  transform: translateY(0);
}

.indicator-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.indicator-key {
  font-weight: bold;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 4px;
}

.indicator-action {
  font-size: 14px;
}
</style>
